<?php

namespace plugin\admin\app\service\v1;

use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\model\Admin;
use plugin\admin\app\model\V1UserExtend;
use plugin\admin\app\model\V1UserLinkExtend;
use support\exception\BusinessException;

/**
 * 会员推广权限服务类
 **/
class UserExtendService
{

    /**
     * 指定会员的推广权限
     *
     * @param integer $user_id
     * @param array $admin
     * @param integer $type 类型:0=全部(上级+自己),1=上级,2=自己
     **/
    public static function getUserExtendParent($user_id, $admin, $type = 0)
    {
        if ($type == 2) {
//            $exchange_user_list = OrderService::orderNumber($admin, 4);
//            $exchange_user_list = array_column($exchange_user_list, null, 'line_id');
            list($line_list, $line_column) = LineService::select();
            $user_extend = self::getUserExtend($line_column, $admin);
            $user_extend = self::addNameToExtend($line_column, $user_extend,[]);
            return [[], $user_extend, [],[]];
        }

        // 会员信息
        $user = Admin::where('id', $user_id)->select(['id', 'invitation_id'])->first()->toArray();
        if (!$user) {
            throw new BusinessException('会员不存在！');
        }

        list($line_list, $line_column) = LineService::select();
        if ($admin['user_status'] == CommonConstant::DEFAULT_1) {
            // 管理员身份处理
            if (!$user['invitation_id']) {
                // 会员无邀请人
                foreach ($line_list as $key => $value) {
                    $line_list[$key]['line_id'] = $line_list[$key]['id'];
                }
                $parent_user_extend = $line_list;
            } else {
                $parent = Admin::where('id', $user['invitation_id'])->select(['id'])->first()->toArray();
                $parent_user_extend = self::getUserExtend($line_column, $parent);
                $parent_user_extend = self::addNameToExtend($line_column, $parent_user_extend);
            }
        } else {
            // 会员身份处理
            if ($admin['id'] != $user['invitation_id']) {
                throw new BusinessException('该会员不是您的下级！');
            }
            $parent = $admin;
            $parent_user_extend = self::getUserExtend($line_column, $parent);
            $parent_user_extend = self::addNameToExtend($line_column, $parent_user_extend);
        }
        $user_extend = [];
        if ($type == 0) {
            $user_extend = self::getUserExtend($line_column, $user);
            $user_extend = self::addNameToExtend($line_column, $user_extend);
        }
        return [
            $parent_user_extend, // 上级用户的推广权限
            $user_extend, // 指定会员的推广权限
            $line_column, // 线路数据
            $user, // 指定用户信息
        ];
    }

    /**
     * 编辑
     *
     * @param array $params
     * @param array $admin
     **/
    public static function edit($params, $admin)
    {
        $extend_data = $params['data'];
        list($parent_user_extend, $user_extend, $line_column,$user) = self::getUserExtendParent($params['user_id'], $admin, 1);
        $extend_data = self::AdminExtendCheck($line_column, $parent_user_extend, $extend_data, $user);
        Util::db()->transaction(function () use ($params, $admin, $extend_data) {
            $user_extend_list = V1UserExtend::where('user_id', $params['user_id'])->get();
            $extend_column = array_column($extend_data, null, 'line_id');
            foreach ($extend_column as $key => $value) {
                unset($extend_column[$key]['rp_show'], $extend_column[$key]['zp_show'], $extend_column[$key]['yp1_show'], $extend_column[$key]['yp3_show'], $extend_column[$key]['yp6_show'], $extend_column[$key]['np_show']);
            }
            foreach ($user_extend_list as $info) {
                $extend_info = $extend_column[$info['line_id']] ?? null;
                if ($extend_info) {
                    doUpdate($extend_info, $info);
                    unset($extend_column[$info['line_id']]);
                }
            }
            if ($extend_column) {
                $insetData = array_map(function ($item) use ($params) {
                    $item['user_id'] = $params['user_id'];
                    return $item;
                }, $extend_column);
                V1UserExtend::insert($insetData);
            }
        });
        return true;
    }

    /**
     * 注册场景根据推广链接获取推广权限
     *
     * @param string $invitation
     * @param string $link_id
     **/
    public static function getUserExtendData($invitation, $link_id)
    {
        $invitation_info = null;
        $extend_data = [];
        if ($invitation) {
            // 推广人信息
            $invitation_info = Admin::where('username', $invitation)
                ->where('user_status', CommonConstant::DEFAULT_2)
                ->first(['id', 'invitation_id']);
            if (!$invitation_info) {
                throw new BusinessException('推广人信息不存在！');
            }

            if ($link_id > 0) {
                // 自定义推广链接权限
                $list = V1UserExtend::where('user_id', $invitation_info['id'])->get()->toArray();
                $list2 = V1UserLinkExtend::where('user_id', $invitation_info['id'])->where('link_id', $link_id)->get()->toArray();
                $list_column = array_column($list2, null, 'line_id');
                foreach ($list as $key => $value) {
                    $info = $list_column[$value['line_id']] ?? null;
                    if ($info) {
                        $data['line_id'] = $info['line_id'];
                        $data['test_number'] = $info['test_number'];
                        $data['test_switch'] = $list[$key]['test_switch'];
                        $data['test2h_switch'] = $list[$key]['test2h_switch'];
                        $data['test6h_switch'] = $list[$key]['test6h_switch'];
                        $data['test12h_switch'] = $list[$key]['test12h_switch'];
                        $data['max_exchange_number'] = $info['max_exchange_number'];
                        $data['rp'] = $info['rp'];
                        $data['zp'] = $info['zp'];
                        $data['yp1'] = $info['yp1'];
                        $data['yp3'] = $info['yp3'];
                        $data['yp6'] = $info['yp6'];
                        $data['np'] = $info['np'];
                        $data['rp_switch'] = $info['rp_switch'];
                        $data['zp_switch'] = $info['zp_switch'];
                        $data['yp1_switch'] = $info['yp1_switch'];
                        $data['yp3_switch'] = $info['yp3_switch'];
                        $data['yp6_switch'] = $info['yp6_switch'];
                        $data['np_switch'] = $info['np_switch'];
                        $data['order_node_refund_switch'] = $value['order_node_refund_switch'];
                        $data['order_node_refund_time'] = $value['order_node_refund_time'];
                        $data['order_node_refund_number'] = $value['order_node_refund_number'];
                        $extend_data[] = $data;
                    }
                }
            } else {
                // 会员推广权限
                $list = V1UserExtend::where('user_id', $invitation_info['id'])->get()->toArray();
                foreach ($list as $key => $value) {
                    unset($list[$key]['id'], $list[$key]['user_id']);
                    $extend_data[] = $list[$key];
                }
            }
        } else {
            // 没有推广人 获取系统推广权限
            list($list, $line_column) = LineService::select();
            foreach ($list as $key => $value) {
                $list[$key]['line_id'] = $list[$key]['id'];
                unset(
                    $list[$key]['id'],
                    $list[$key]['deleted'],
                    $list[$key]['type'],
                    $list[$key]['name'],
                    $list[$key]['weight'],
                    $list[$key]['line_ids'],
                    $list[$key]['status'],
                    $list[$key]['rp_show'],
                    $list[$key]['zp_show'],
                    $list[$key]['yp1_show'],
                    $list[$key]['yp3_show'],
                    $list[$key]['yp6_show'],
                    $list[$key]['np_show']
                );
                $extend_data[] = $list[$key];
            }
        }
        return [$invitation_info, $extend_data];
    }

    /**
     * 获取会员推广权限
     *
     * @param array $line_column
     * @param array $admin
     **/
    public static function getUserExtend($line_column, $admin)
    {
        $line_ids = array_keys($line_column);
        $query = V1UserExtend::where('user_id', $admin['id'])
            ->whereIn('line_id', $line_ids)
            ->get();
        $user_extend = $query->toArray();
        $user_extend_column = $query->keyBy('line_id')->toArray();

        $user_extend_data = [];
        foreach ($line_column as $item) {
            $extend = $user_extend_column[$item['id']] ?? null;
            if ($extend) {
                $user_extend_data[$item['id']] = $extend;
            }
        }
        return array_values($user_extend_data);
    }

    /**
     * 为推广权限数据添加名称字段
     *
     * @param array $lineColumn 线路配置数据
     * @param array $extendData 推广权限数据
     * @param array $exchange_user_list 已调换数量数据
     * @return array 处理后的推广权限数据
     */
    public static function addNameToExtend(array $lineColumn, array $extendData, $exchange_user_list = []): array
    {
        return array_map(function ($item) use ($lineColumn, $exchange_user_list) {
            $line = $lineColumn[$item['line_id']] ?? null;
            $item['name'] = $line['name'] ?? '';
            $item['rp_show'] = $line['rp_show'] ?? 0;
            $item['zp_show'] = $line['zp_show'] ?? 0;
            $item['yp1_show'] = $line['yp1_show'] ?? 0;
            $item['yp3_show'] = $line['yp3_show'] ?? 0;
            $item['yp6_show'] = $line['yp6_show'] ?? 0;
            $item['np_show'] = $line['np_show'] ?? 0;
            $item['np_show'] = $line['np_show'] ?? 0;
            $exchange_user = $exchange_user_list[$item['line_id']]['number'] ?? 0;
            $surplus_exchange_number = $item['max_exchange_number'] - $exchange_user;
            $item['surplus_exchange_number'] = $surplus_exchange_number > 0 ? $surplus_exchange_number : 0;
            return $item;
        }, $extendData);
    }


    /**
     * 验证会员推广链接权限
     *
     * @param array $line_column
     * @param array $user_extend
     * @param array $extend_data
     **/
    public static function UserExtendCheck($line_column, $user_extend, $extend_data)
    {
        $data = [];
        $extend_data_column = array_column($extend_data, null, 'line_id');
        foreach ($user_extend as $key => $value) {
            $name = $line_column[$user_extend[$key]['line_id']]['name'] ?? '';

            $info = $extend_data_column[$value['line_id']] ?? null;
            if ($info) {

                if ($value['test_number'] < $info['test_number']) {
                    throw new BusinessException($name . '测试卡数量不能超过当前用户测试卡数量！');
                }

                if ($value['max_exchange_number'] < $info['max_exchange_number']) {
                    throw new BusinessException($name . '最大调换数量不能超过当前用户最大调换数量！');
                }

                if ($info['rp_show'] == CommonConstant::DEFAULT_1) {
                    if ($value['rp'] > $info['rp']) {
                        throw new BusinessException($name . '日卡价格不能低于当前用户日卡价格！');
                    }
                    if ($value['rp_switch'] == CommonConstant::DEFAULT_0) {
                        $info['rp_switch'] = CommonConstant::DEFAULT_0;
                        $info['rp'] = $value['rp'];
                    }
                } else {
                    $info['rp_switch'] = CommonConstant::DEFAULT_0;
                    $info['rp'] = $value['rp'];
                }

                if ($info['zp_show'] == CommonConstant::DEFAULT_1) {
                    if ($value['zp'] > $info['zp']) {
                        throw new BusinessException($name . '周卡价格不能低于当前用户周卡价格！');
                    }
                    if ($value['zp_switch'] == CommonConstant::DEFAULT_0) {
                        $info['zp_switch'] = CommonConstant::DEFAULT_0;
                        $info['zp'] = $value['zp'];
                    }
                } else {
                    $info['zp_switch'] = CommonConstant::DEFAULT_0;
                    $info['zp'] = $value['zp'];
                }

                if ($info['yp1_show'] == CommonConstant::DEFAULT_1) {
                    if ($value['yp1'] > $info['yp1']) {
                        throw new BusinessException($name . '月卡价格不能低于当前用户月卡价格！');
                    }
                    if ($value['yp1_switch'] == CommonConstant::DEFAULT_0) {
                        $info['yp1_switch'] = CommonConstant::DEFAULT_0;
                        $info['yp1'] = $value['yp1'];
                    }
                } else {
                    $info['yp1_switch'] = CommonConstant::DEFAULT_0;
                    $info['yp1'] = $value['yp1'];
                }

                if ($info['yp3_show'] == CommonConstant::DEFAULT_1) {
                    if ($value['yp3'] > $info['yp3']) {
                        throw new BusinessException($name . '季卡价格不能低于当前用户季卡价格！');
                    }
                    if ($value['yp3_switch'] == CommonConstant::DEFAULT_0) {
                        $info['yp3_switch'] = CommonConstant::DEFAULT_0;
                        $info['yp3'] = $value['yp3'];
                    }
                } else {
                    $info['yp3_switch'] = CommonConstant::DEFAULT_0;
                    $info['yp3'] = $value['yp3'];
                }

                if ($info['yp6_show'] == CommonConstant::DEFAULT_1) {
                    if ($value['yp6'] > $info['yp6']) {
                        throw new BusinessException($name . '半年卡价格不能低于当前用户半年卡价格！');
                    }
                    if ($value['yp6_switch'] == CommonConstant::DEFAULT_0) {
                        $info['yp6_switch'] = CommonConstant::DEFAULT_0;
                        $info['yp6'] = $value['yp6'];
                    }
                } else {
                    $info['yp6_switch'] = CommonConstant::DEFAULT_0;
                    $info['yp6'] = $value['yp6'];
                }

                if ($info['np_show'] == CommonConstant::DEFAULT_1) {
                    if ($value['np'] > $info['np']) {
                        throw new BusinessException($name . '年卡价格不能低于当前用户年卡价格！');
                    }
                    if ($info['np_switch'] == CommonConstant::DEFAULT_0) {
                        $info['np_switch'] = CommonConstant::DEFAULT_0;
                        $info['np'] = $value['np'];
                    }
                } else {
                    $info['np_switch'] = CommonConstant::DEFAULT_0;
                    $info['np'] = $value['np'];
                }

                $data[] = $info;
            }
        }
        return $data;
    }

    /**
     * 验证会员推广权限
     *
     * @param array $line_column
     * @param array $user_extend
     * @param array $extend_data
     **/
    public static function AdminExtendCheck($line_column, $user_extend, $extend_data, $user)
    {
        $data = [];
        if ($user['invitation_id'] > 0 ) {
            $extend_data_column = array_column($extend_data, null, 'line_id');
            foreach ($user_extend as $key => $value) {
                $name = $line_column[$user_extend[$key]['line_id']]['name'] ?? '';

                $info = $extend_data_column[$value['line_id']] ?? null;
                if ($info) {

                    if ($value['test_number'] < $info['test_number']) {
                        throw new BusinessException('不能超过上级代理的数量(' . $name . '/测试卡/' . $value['test_number'] . ')！');
                    }

                    if ($value['max_exchange_number'] < $info['max_exchange_number']) {
                        throw new BusinessException('不能超过上级代理的数量(' . $name . '/最大调换数量/' . $value['max_exchange_number'] . ')！');
                    }

                    if ($value['rp_show'] == CommonConstant::DEFAULT_1) {
                        if ($value['rp'] > $info['rp']) {
                            throw new BusinessException('不能低于上级代理的价格(' . $name . '/日卡/' . $value['rp'] . ')！');
                        }
                        if ($value['rp_switch'] == CommonConstant::DEFAULT_0) {
                            $info['rp_switch'] = CommonConstant::DEFAULT_0;
                            $info['rp'] = $value['rp'];
                        }
                    } else {
                        $info['rp_switch'] = CommonConstant::DEFAULT_0;
                        $info['rp'] = $value['rp'];
                    }

                    if ($value['zp_show'] == CommonConstant::DEFAULT_1) {
                        if ($value['zp'] > $info['zp']) {
                            throw new BusinessException('不能低于上级代理的价格(' . $name . '/周卡/' . $value['zp'] . ')！');
                        }
                        if ($value['zp_switch'] == CommonConstant::DEFAULT_0) {
                            $info['zp_switch'] = CommonConstant::DEFAULT_0;
                            $info['zp'] = $value['zp'];
                        }
                    } else {
                        $info['zp_switch'] = CommonConstant::DEFAULT_0;
                        $info['zp'] = $value['zp'];
                    }

                    if ($value['yp1_show'] == CommonConstant::DEFAULT_1) {
                        if ($value['yp1'] > $info['yp1']) {
                            throw new BusinessException('不能低于上级代理的价格(' . $name . '/月卡/' . $value['yp1'] . ')！');
                        }
                        if ($value['yp1_switch'] == CommonConstant::DEFAULT_0) {
                            $info['yp1_switch'] = CommonConstant::DEFAULT_0;
                            $info['yp1'] = $value['yp1'];
                        }
                    } else {
                        $info['yp1_switch'] = CommonConstant::DEFAULT_0;
                        $info['yp1'] = $value['yp1'];
                    }

                    if ($value['yp3_show'] == CommonConstant::DEFAULT_1) {
                        if ($value['yp3'] > $info['yp3']) {
                            throw new BusinessException('不能低于上级代理的价格(' . $name . '/季卡/' . $value['yp3'] . ')！');
                        }
                        if ($value['yp3_switch'] == CommonConstant::DEFAULT_0) {
                            $info['yp3_switch'] = CommonConstant::DEFAULT_0;
                            $info['yp3'] = $value['yp3'];
                        }
                    } else {
                        $info['yp3_switch'] = CommonConstant::DEFAULT_0;
                        $info['yp3'] = $value['yp3'];
                    }

                    if ($value['yp6_show'] == CommonConstant::DEFAULT_1) {
                        if ($value['yp6'] > $info['yp6']) {
                            throw new BusinessException('不能低于上级代理的价格(' . $name . '/半年卡/' . $value['yp6'] . ')！');
                        }
                        if ($value['yp6_switch'] == CommonConstant::DEFAULT_0) {
                            $info['yp6_switch'] = CommonConstant::DEFAULT_0;
                            $info['yp6'] = $value['yp6'];
                        }
                    } else {
                        $info['yp6_switch'] = CommonConstant::DEFAULT_0;
                        $info['yp6'] = $value['yp6'];
                    }

                    if ($value['np_show'] == CommonConstant::DEFAULT_1) {
                        if ($value['np'] > $info['np']) {
                            throw new BusinessException('不能低于上级代理的价格(' . $name . '/年卡/' . $value['np'] . ')！');
                        }
                        if ($value['np_switch'] == CommonConstant::DEFAULT_0) {
                            $info['np_switch'] = CommonConstant::DEFAULT_0;
                            $info['np'] = $value['np'];
                        }
                    } else {
                        $info['np_switch'] = CommonConstant::DEFAULT_0;
                        $info['np'] = $value['np'];
                    }

                    if ($value['order_node_refund_switch'] == CommonConstant::DEFAULT_1) {
                        if ($value['order_node_refund_time'] < $info['order_node_refund_time']) {
                            throw new BusinessException('不能高于上级代理的退款时间(' . $name . '/退款时间/' . $value['order_node_refund_time'] . ')！');
                        }
                        if ($value['order_node_refund_number'] < $info['order_node_refund_number']) {
                            throw new BusinessException('不能超过上级代理的退款数量(' . $name . '/退款数量/' . $value['order_node_refund_number'] . ')！');
                        }
                    } else{
                        $info['order_node_refund_switch'] = CommonConstant::DEFAULT_0;
                        $info['order_node_refund_time'] = 0;
                        $info['order_node_refund_number'] = 0;
                    }

                    $data[] = $info;
                }
            }
        } else{
            $data = $extend_data;
        }

        $db = Util::db();
        $user_ids = $db->table('wa_admins')->where('invitation_id', $user['id'])->pluck('id')->toArray();
        if ($user_ids) {
            foreach ($data as $key => $item) {
                $name = $line_column[$user_extend[$key]['line_id']]['name'] ?? '';

                if ($item['rp_show'] == CommonConstant::DEFAULT_1) {
                    $min_rp = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('rp', '<', $item['rp'])->value('rp');
                    if ($min_rp) {
                        throw new BusinessException('不能高于下级代理的价格(' . $name . '/日卡/' . $min_rp . ')！');
                    }
                }

                if ($item['zp_show'] == CommonConstant::DEFAULT_1) {
                    $min_zp = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('zp', '<', $item['zp'])->value('zp');
                    if ($min_zp) {
                        throw new BusinessException('不能高于下级代理的价格(' . $name . '/周卡/' . $min_zp . ')！');
                    }
                }

                if ($item['yp1_show'] == CommonConstant::DEFAULT_1) {
                    $min_yp1 = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('yp1', '<', $item['yp1'])->value('yp1');
                    if ($min_yp1) {
                        throw new BusinessException('不能高于下级代理的价格(' . $name . '/月卡/' . $min_yp1 . ')！');
                    }
                }

                if ($item['yp3_show'] == CommonConstant::DEFAULT_1) {
                    $min_yp3 = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('yp3', '<', $item['yp3'])->value('yp3');
                    if ($min_yp3) {
                        throw new BusinessException('不能高于下级代理的价格(' . $name . '/季卡/' . $min_yp3 . ')！');
                    }
                }

                if ($item['yp6_show'] == CommonConstant::DEFAULT_1) {
                    $min_yp6 = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('yp6', '<', $item['yp6'])->value('yp6');
                    if ($min_yp6) {
                        throw new BusinessException('不能高于下级代理的价格(' . $name . '/半年卡/' . $min_yp6 . ')！');
                    }
                }

                if ($item['np_show'] == CommonConstant::DEFAULT_1) {
                    $min_np = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('np', '<', $item['np'])->value('np');
                    if ($min_np) {
                        throw new BusinessException('不能高于下级代理的价格(' . $name . '/年卡/' . $min_np . ')！');
                    }
                }

                if($item['order_node_refund_switch'] == CommonConstant::DEFAULT_1){
                    $min_order_node_refund_time = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('order_node_refund_time', '>', $item['order_node_refund_time'])->value('order_node_refund_time');
                    if ($min_order_node_refund_time) {
                        throw new BusinessException('不能低于下级代理的退款时间(' . $name . '/退款时间/' . $min_order_node_refund_time . ')！');
                    }

                    $min_order_node_refund_number = $db->table('wa_v1_user_extend')->where('line_id', $item['line_id'])->whereIn('user_id', $user_ids)->where('order_node_refund_number', '>', $item['order_node_refund_number'])->value('order_node_refund_number');
                    if ($min_order_node_refund_number) {
                        throw new BusinessException('不能低于下级代理的退款数量(' . $name . '/退款数量/' . $min_order_node_refund_number . ')！');
                    }
                }

            }
        }
        return $data;
    }

}
